package com.jy.modules.cims.common.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmExcelDictionaryService;
import com.jy.modules.cims.component.common.service.TCMmExcelTemplateService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.common.dto.TCMmExcelDictionaryDTO;
import com.jy.modules.cims.data.common.dto.TCMmExcelTemplateDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;

/**
 * @classname: TCMmExcelTemplateController
 * @description: 定义  T_C_MM_EXCEL_TEMPLATE 控制层
 * @author:  JY-IT-D001
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmExcelTemplate")
public class TCMmExcelTemplateController extends CimsBaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmExcelTemplateController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmExcelTemplateService")
    private TCMmExcelTemplateService service;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmExcelDictionaryService")
    private TCMmExcelDictionaryService dictionaryservice;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQuery".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/modelManage/queryTCMmExcelTemplate");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/modelManage/addTCMmExcelTemplate");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/modelManage/updateTCMmExcelTemplate");								
        }else if("toCopy".equals(operate)){//跳转至 复制页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/modelManage/copyTCMmExcelTemplate");
        										
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/modelManage/viewTCMmExcelTemplate");
        }else if("toSelect".equals(operate)){//跳转至 模板选择页面
        	model.setViewName("cims/modelManage/queryTCMmSelectTemplate");
        }
        
        return model;
    }
    
    /**
     * @author JY-IT-D001
     * @description:查询分页列表
     * @date 2015-01-06 17:32:59
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmExcelTemplate")
    @ResponseBody
    public DataMsg queryListTCMmExcelTemplate(HttpServletRequest request, TCMmExcelTemplateDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmExcelTemplateDTO> list = service.searchTCMmExcelTemplateByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    @SuppressWarnings("null")
	@RequestMapping(value = "/isTCMmExcelTemplate")
    @ResponseBody
    public DataMsg isTCMmExcelTemplate(HttpServletRequest request, TCMmExcelTemplateDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
		TCMmExcelTemplateDTO templateDTO = service.findTCMmExcelTemplateByContractCode(params
                .getSearchParams());
        String templateCode = templateDTO.getTemplateCode();
        String templateCodeNew = dto.getTemplateCode();
        List<TCMmExcelDictionaryDTO> list = null;
        List<TCMmExcelDictionaryDTO> listNew = null;
		if(SimpleStringUtils.hasText(templateCode)){
			list = dictionaryservice.queryTCMmExcelDictionaryByTemplateCodes(templateCode);
		}else {
			listNew = dictionaryservice.queryTCMmExcelDictionaryByTemplateCodes(templateCodeNew);
			int listNewLength = listNew.size();
			if(listNewLength>=1){
				list = listNew;
			}
		}
		
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    

    /**
     * @author JY-IT-D001
     * @description:新增
     * @date 2015-01-06 17:32:59
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmExcelTemplate")
    @ResponseBody
    public DataMsg insertTCMmExcelTemplate(HttpServletRequest request, TCMmExcelTemplateDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmExcelTemplateDTO)super.initDto(dto);

            service.insertTCMmExcelTemplate(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertTCMmExcelTemplate异常：", e);
        }
        return dataMsg;
    }
    
    /**
     * @author JY-IT-D001
     * @description:复制
     * @date 2015-10-15 17:32:59
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/copyTCMmExcelTemplate")
    @ResponseBody
    public DataMsg copyTCMmExcelTemplate(HttpServletRequest request, TCMmExcelTemplateDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmExcelTemplateDTO)super.initDto(dto);

            service.insertTCMmExcelTemplate(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("复制成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertTCMmExcelTemplate异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author JY-IT-D001
     * @description:编辑
     * @date 2015-01-06 17:32:59
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmExcelTemplate")
    @ResponseBody
    public DataMsg updateTCMmExcelTemplate(HttpServletRequest request, TCMmExcelTemplateDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmExcelTemplateDTO)super.initDto(dto);
           
            service.updateTCMmExcelTemplate(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author JY-IT-D001
     * @description:删除
     * @date 2015-01-06 17:32:59
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmExcelTemplate")
    @ResponseBody
    public DataMsg deleteTCMmExcelTemplate(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	String templateCodes = (String) this.getParameter("templateCode");
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 service.deleteTCMmExcelTemplateByPrimaryKey(dto,ids);
			 String templateCode[] = templateCodes.split(",");
			 for (int i = 0; i < templateCode.length; i++) {
				 dictionaryservice.deleteTCMmExcelDictionaryByTemplateCode(templateCode[i]);
			}
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e.getMessage());

		}
        
        return dataMsg;
    }
    /**
     * @author JY-IT-D001
     * @description:通过主键查询 其明细信息
     * @date 2015-01-06 17:32:59
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmExcelTemplateDTO dto = service.queryTCMmExcelTemplateByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    /**
     * 导出空模板
     * @throws IOException 
     */
    @RequestMapping(value = "/exportNullTemplate")
    @ResponseBody
    public void exportNullTemplate(HttpServletResponse response,@ModelAttribute DataMsg dataMsg) throws IOException{
    	String contractCode = new String(this.getParameterString("contractCode").getBytes("iso8859-1"),"utf-8");
		String templateType = this.getParameterString("templateType");
		String fileName = this.getParameterString("fileName");
    	ExportAndImport<CreditDetailDto> exportAndImport = new ExportAndImport<CreditDetailDto>();
		HSSFWorkbook workbook;
		try {
			workbook = exportAndImport.exportExcel(fileName, contractCode, templateType, null);
		
			fileName = exportAndImport.fileNameOperation(contractCode, templateType);
			write(workbook, fileName, response);
		} catch (IOException e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
		}
    }
    
    /**
	 * 页面输出
	 * 
	 * @param workbook
	 * @param fileName
	 * @param response
	 * @throws IOException
	 */
	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

		try {
			response.setContentType("application/vnd.ms-excel");
			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
			workbook.write(response.getOutputStream());
			response.getOutputStream().flush();
		} catch (Exception e) {
			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
		} finally {
			response.getOutputStream().close();
		}
	}
}
